package com.gxc.webcore.util;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * 
 * Bean-Map转换工具类
 * 
 * @author gxc
 * 
 */
@SuppressWarnings("rawtypes")
public class MapUtil {

	public static Object map2bean(Map map, Class clazz) {
		Object objInstance = null;
		try {
			objInstance = clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BeanWrapper beanWrapper = new BeanWrapperImpl(objInstance);
		// 循环属性说明
		for (PropertyDescriptor descriptor : beanWrapper
				.getPropertyDescriptors()) {
			String name = descriptor.getName();
			Class<?> type = descriptor.getPropertyType();
			// 处理可写属性
			if (beanWrapper.isWritableProperty(name)) {
				// 从请求中查询参数,并转换为相应的类型
				Object value = ConvertUtil.object2Object(type, map.get(name));
				beanWrapper.setPropertyValue(name, value);
			}
		}
		return objInstance;
	}

	@SuppressWarnings("unchecked")
	public static HashMap bean2map(Object bean) {
		HashMap map = new HashMap();
		BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
		// 循环属性说明
		for (PropertyDescriptor descriptor : beanWrapper
				.getPropertyDescriptors()) {
			String name = descriptor.getName();
			// 处理可读属性
			if (beanWrapper.isReadableProperty(name)) {
				// 从请求中查询参数,并转换为相应的类型
				Object value = beanWrapper.getPropertyValue(name);
				map.put(name, value);
			}
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public static List maplist2beanlist(List list, Class clazz) {
		List beanList = new ArrayList();
		for (Map map : (List<Map>) list) {
			beanList.add(map2bean(map, clazz));
		}
		return beanList;
	}

	@SuppressWarnings("unchecked")
	public static List beanlist2maplist(List list, Class clazz) {
		List mapList = new ArrayList();
		for (Object bean : list) {
			mapList.add(bean2map(bean));
		}
		return mapList;
	}

}
